package world

import (
	"context"
	"github.com/topfreegames/pitaya"
	"github.com/topfreegames/pitaya/component"
	"github.com/topfreegames/pitaya/fairy/constants"
	"github.com/topfreegames/pitaya/fairy/manager"
	"github.com/topfreegames/pitaya/fairy/protos"
)

type GameDealer struct {
	component.Base
}

func NewGameDealer() *GameDealer {
	return &GameDealer{}
}

func (p *GameDealer) PlayerAuth(ctx context.Context,req *protos.GWPlayerAuth) (*protos.WGPlayerAuthRet,error) {
	maxConnectNum := pitaya.GetConfig().GetInt("pitaya.game.worldserver.maxpoolplayersize")
	onlineCount := manager.OnlinePlayerManager.GetServerOnlinePlayerCount(*req.ServerId)
	if onlineCount >= maxConnectNum {
		return &protos.WGPlayerAuthRet{
			RetCode:    &constants.PlayerPoolFull,
		},nil
	}

	playerInfo := manager.OnlinePlayerManager.GetPlayerInfoByAccount(*req.AccountId,*req.AppId)
	if playerInfo == nil {
		return &protos.WGPlayerAuthRet{
			RetCode:    &constants.PlayereUnloginError,
		},nil
	}

	if *req.Ticket != playerInfo.Ticket {
		return &protos.WGPlayerAuthRet{
			RetCode:    &constants.PlayerTicketError,
		},nil
	}

	if playerInfo.FullData == nil {
		return &protos.WGPlayerAuthRet{
			RetCode:    &constants.PlayerNoDataError,
		},nil
	}


	playerInfo.ServerId = *req.ServerId
	manager.OnlinePlayerManager.SetPlayerOnline(*req.AccountId,*req.AppId)
	if playerInfo.GangId > 0 {
		//todo:通知战队玩家上线
	}
	playerInfo.FullData = nil

	return &protos.WGPlayerAuthRet{
		PlayerData: playerInfo.FullData,
		RetCode:    &constants.InitGameAutuSuccess,
	},nil
}
